package blog.utils;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
/**
 * 图片处理
 * @author 14560
 *
 */
public class ImageUtil {
	private Image img;
	private final static int WIDTH = 100;
	private final static int HEIGHT = 100;

	/**
	 * 改变图片的大小到宽为size，然后高随着宽等比例变化
	 * 
	 * @param is     上传的图片的输入流
	 * @param size   新图片的宽
	 * @param format 新图片的格式
	 * @throws IOException
	 */
	public static byte[] resizeImage(byte[] bs, int size, String format)
			throws IOException {
		if(bs.length==0) {
			return null;
		}
		OutputStream os=new ByteArrayOutputStream();
		InputStream is = new ByteArrayInputStream(bs); 
		BufferedImage prevImage = ImageIO.read(is);
		double width = prevImage.getWidth();
		double height = prevImage.getHeight();
		double percent = size / width;
		int newWidth = (int) (width * percent);
		int newHeight = (int) (height * percent);
		BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR);
		Graphics graphics = image.createGraphics();
		graphics.drawImage(prevImage, 0, 0, newWidth, newHeight, null);
		ImageIO.write(image, format, os);
		os.flush();
		is.close();
		os.close();
		ByteArrayOutputStream b = (ByteArrayOutputStream) os;
		return b.toByteArray();
	}
	
	/**
	 * 根据email获取gravatar头像
	 * @param email Email
	 * @return 头像URL
	 */
	public static String getGravatar(String email) {
		//设置图片大小32px
		return "http://cn.gravatar.com/avatar/" +  MD5Util.strToMd5(email) + "?s=128&d=identicon&r=PG";
	}
}
